import http from './request.js';
import { formatDate } from './utils.js';

class NoticeDetail {
    constructor() {
        this.noticeDetail = document.getElementById('noticeDetail');
        this.commentsList = document.getElementById('commentsList');
        this.postId = new URLSearchParams(window.location.search).get('id');
        this.init();
    }

    init() {
        if (!this.postId) {
            alert('Invalid post ID');
            window.location.href = './index.html';
            return;
        }
        this.loadPostDetail();
        this.bindEvents();
    }

    async loadPostDetail() {
        try {
            const post = await http.get(`/posts/${this.postId}`);
            this.renderDetail(post);
            this.loadComments();
        } catch (error) {
            console.error('Failed to load post detail:', error);
            alert('Failed to load post detail: ' + error.message);
        }
    }

    renderDetail(post) {
        this.noticeDetail.innerHTML = `
            <div class="detail-header">
                <div class="detail-title-row">
                    <div class="notice-tags">
                        ${post.TagName ? `
                            <span class="tag tag-category">${http.escapeHtml(post.TagName)}</span>
                        ` : ''}
                        ${post.IsHot ? `
                            <span class="tag tag-hot">Popular</span>
                        ` : ''}
                    </div>
                    <h2 class="detail-title">${http.escapeHtml(post.Title)}</h2>
                </div>
                <div class="detail-meta">
                    <div class="detail-author">
                        <img src="${http.escapeHtml(post.AuthorAvatar || '../assets/images/default_photo.jpg')}" 
                             alt="${http.escapeHtml(post.AuthorName)}" 
                             class="author-avatar">
                        <span class="author-name">${http.escapeHtml(post.AuthorName)}</span>
                    </div>
                    <span class="detail-date">${formatDate(post.CreateTime)}</span>
                </div>
            </div>

            ${post.Media ? `
                <div class="detail-media-container">
                    ${post.Media.split(',').map(mediaPath => `
                        <div class="detail-media">
                            ${mediaPath.toLowerCase().endsWith('.mp4') ? `
                                <video src="${http.escapeHtml(mediaPath)}" controls class="media-content">
                                    Your browser does not support the video tag.
                                </video>
                            ` : `
                                <img src="${http.escapeHtml(mediaPath)}" alt="Post media" class="media-content">
                            `}
                        </div>
                    `).join('')}
                </div>
            ` : ''}

            <div class="detail-content">
                ${http.formatContent(post.Content)}
            </div>

            <div class="detail-actions">
                <div class="action-left">
                    <button class="action-btn like-btn ${post.IsLiked ? 'active' : ''}" onclick="noticeDetail.handleLike()">
                        <i class="icon">👍</i>
                        <span>${post.LikeCount}</span>
                    </button>
                    <button class="action-btn comment-btn">
                        <i class="icon">💬</i>
                        <span>${post.CommentCount}</span>
                    </button>
                    <button class="action-btn share-btn" onclick="noticeDetail.handleShare()">
                        <i class="icon">🔗</i>
                        Share
                    </button>
                </div>
                ${post.StudentID === http.getUserInfo()?.id ? `
                    <div class="action-right">
                        <button class="action-btn edit-btn" onclick="noticeDetail.handleEdit()">
                            <i class="icon">✏️</i>
                            Edit
                        </button>
                        <button class="action-btn delete-btn" onclick="noticeDetail.handleDelete()">
                            <i class="icon">🗑️</i>
                            Delete
                        </button>
                    </div>
                ` : ''}
            </div>
        `;
    }

    async loadComments() {
        try {
            const comments = await http.get(`/posts/${this.postId}/comments`);
            this.renderComments(comments);
        } catch (error) {
            console.error('Failed to load comments:', error);
            alert('Failed to load comments: ' + error.message);
        }
    }

    renderComments(comments) {
        this.commentsList.innerHTML = `
            ${comments.map(comment => `
                <div class="comment-item" data-id="${comment.CommentID}">
                    <div class="comment-header">
                        <div class="comment-author">
                            <img src="${http.escapeHtml(comment.AuthorAvatar || '../assets/images/default_photo.jpg')}" 
                                 alt="${http.escapeHtml(comment.AuthorName)}" 
                                 class="comment-avatar">
                            <div class="comment-info">
                                <span class="comment-author-name">${http.escapeHtml(comment.AuthorName)}</span>
                                <span class="comment-date">${formatDate(comment.CreateTime)}</span>
                            </div>
                        </div>
                        ${comment.StudentID === http.getUserInfo()?.id ? `
                            <button class="delete-comment-btn" onclick="noticeDetail.deleteComment(${comment.CommentID})">
                                <i class="icon">🗑️</i>
                            </button>
                        ` : ''}
                    </div>
                    <div class="comment-content">${http.formatContent(comment.Content)}</div>
                </div>
            `).join('')}
        `;
    }

    async submitComment() {
        const commentInput = document.querySelector('.comment-input');
        const content = commentInput.value.trim();
        
        if (!content) {
            alert('Please write something');
            return;
        }

        try {
            await http.post(`/posts/${this.postId}/comments`, { content });
            commentInput.value = '';
            await Promise.all([
                this.loadComments(),
                this.loadPostDetail()
            ]);
        } catch (error) {
            console.error('Failed to submit comment:', error);
            alert('Failed to submit comment: ' + error.message);
        }
    }

    async deleteComment(commentId) {
        if (!confirm('Are you sure you want to delete this comment?')) {
            return;
        }

        try {
            await http.delete(`/posts/${this.postId}/comments/${commentId}`);
            await Promise.all([
                this.loadComments(),
                this.loadPostDetail()
            ]);
        } catch (error) {
            console.error('Failed to delete comment:', error);
            alert('Failed to delete comment: ' + error.message);
        }
    }

    bindEvents() {
        const commentForm = document.querySelector('.comment-form');
        const commentInput = document.querySelector('.comment-input');
        
        if (commentForm && commentInput) {
            commentForm.querySelector('button').addEventListener('click', () => {
                const content = commentInput.value.trim();
                if (content) {
                    this.submitComment();
                }
            });
        }
    }

    async handleLike() {
        try {
            await http.post(`/posts/${this.postId}/like`);
            // 重新加载帖子详情以更新点赞状态
            this.loadPostDetail();
        } catch (error) {
            console.error('Failed to like post:', error);
            alert('Failed to like post: ' + error.message);
        }
    }

    handleShare() {
        const currentUrl = window.location.href;
        navigator.clipboard.writeText(currentUrl).then(() => {
            alert('Share link copied successfully!');
        }).catch(err => {
            console.error('Failed to copy:', err);
            alert('Failed to copy share link');
        });
    }

    handleEdit() {
        window.location.href = `./post-notice.html?edit=true&id=${this.postId}`;
    }

    async handleDelete() {
        if (confirm('Are you sure you want to delete this post?')) {
            try {
                await http.delete(`/posts/${this.postId}`);
                alert('Post deleted successfully');
                window.location.href = './index.html';
            } catch (error) {
                console.error('Failed to delete post:', error);
                alert('Failed to delete post: ' + error.message);
            }
        }
    }
}

// 创建全局实例
window.noticeDetail = new NoticeDetail(); 